/*
 * @Author: 刘经标 2604132672@qq.com
 * @Date: 2025-04-14 10:25:09
 * @LastEditors: 刘经标 2604132672@qq.com
 * @LastEditTime: 2025-04-14 11:45:12
 * @FilePath: /ai-backend/src/utils/apiErrorHandler.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Request, Response, NextFunction } from 'express';
import { logger } from './logger.js';

export class APIError extends Error {
  constructor(
    public statusCode: number,
    public message: string,
    public isOperational = true
  ) {
    super(message);
  }
}

export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  logger.error(`${err.name}: ${err.message}`);
  
  if (err instanceof APIError) {
    return res.status(err.statusCode).json({
      error: err.message,
      ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
    });
  }

  res.status(500).json({ 
    error: '服务器内部错误',
    ...(process.env.NODE_ENV === 'development' && { details: err.message })
  });
};